<?php

namespace app\api\controller;

use app\api\model\Advert as AdvertModel;
use app\api\model\Category as CategoryModel;
use app\api\model\Special as SpecialModel;
use app\api\model\Goods as GoodsModel;
use app\common\enum\user\balanceLog\Scene as SceneEnum;
use app\store\model\Setting;
use app\store\model\user\BalanceLog as BalanceLogModel;

/**
 * @desc 首页
 */
class Index extends Controller
{
    /**
     * @desc 商城首页
     */
    public function index()
    {
        $advert = AdvertModel::getList();
//        $special = SpecialModel::field('special_id,name,image_id')
//            ->with(['image'=>function($query){$query->field('file_id,storage,file_name');}])
//            ->select();
        $model = new GoodsModel;
        $param = array_merge($this->request->param(), [
            'status' => 10,
        ]);
        // 获取列表数据
        $goods_list = $model->getList($param, $this->getUser(false));
        $full_free = json_decode(Setting::get('full_free'));

        $data = [
            'advert'=>$advert,
            'full_free'=>$full_free,
            'list'=>$goods_list
        ];
        return $this->renderSuccess($data);
    }
    /**
     * @desc 广告
     */
    public function ad()
    {
        $advert = AdvertModel::getList();
        $data = [
            'advert'=>$advert,
        //    'list'=>$list
        ];
        return $this->renderSuccess($data);
    }
    public function bonusesPayment(){
        $k = strtotime("-7 day", time());
       // $e = strtotime("+7 day", time());
        $k_1 = strtotime(date('Y-m-d 00:00:00',$k));
       // $e_1 =  strtotime(date('Y-m-d 23:59:59',$e));
       // $where['receipt_time'] = ['between',[$k_1,$e_1]];
        $where['receipt_time'] = ['ELT',$k_1];
        $list = model('order')->where(['is_settled'=>1,'payment_type'=>1,'receipt_status'=>20])->where($where)->select();
        if(!empty($list)){
            foreach ($list as $value){
                $user_capital = model('user_capital')->where(['order_no'=>$value['order_no'],'type'=>1])->select();
                foreach ($user_capital as $v){
                    //用户加佣金
                    model('user')->where(['user_id'=>$v['user_id']])->setInc('balance',$v['money']);
                    //修改佣金明细表状态
                    model('user_capital')->where(['order_no'=>$v['order_no'],'user_id'=>$v['user_id'],'type'=>1])->setField('type',2);
                    // 新增余额变动记录
                    BalanceLogModel::add(SceneEnum::CAPITAL, [
                        'user_id' => $v['user_id'],
                        'money' => $v['money'],
                        'remark' => '佣金发放',
                    ], [$value['order_no']]);
                }
                //修改订单发放状态
                model('order')->where(['order_no'=>$value['order_no'],'payment_type'=>1])->setField('payment_type',2);
            }
        }
    }

    public function aassdd(){
       $list =  model('user')->where(['referee_id'=>0])->select();
        foreach ($list as $value){
            if($value['referee_phone'] != null && $value['referee_phone'] != '-'){
                $user_id =  model('user')->where(['phone'=>$value['referee_phone'] ])->value('user_id');
                if($user_id){
                    model('user')->where(['user_id'=>$value['user_id'] ])->setField('referee_id',$user_id);
                }
            }
        }
    }

    public function sendsms(){
        $data = $this->request->param();
        if($data['phone']) {
            if (!$data['phone'] || !\think\Validate::regex($data['phone'], "^1\d{10}$")) {
                $this->renderError('手机号不正确');
            }
        }else{
            $this->renderError('手机号不能为空');
        }
        $url = "http://v.juhe.cn/sms/send";
        $code = mt_rand(1000, 9999) ;
        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $where['create_time'] = ['between',"$beginToday,$endToday"];
        $where['phone'] = $data['phone'];

        $count = db('user_sms')->where($where)->count();
        if($count > 10){
            $this->renderError('今日发送短信超过限制数量');
        }
        $params = array(
            'key'   => '94706657cd7d35cbfd87935ae0b845be', //您申请的APPKEY
            'mobile'    => $data['phone'], //接受短信的用户手机号码
            'tpl_id'    => '237980', //您申请的短信模板ID，根据实际情况修改
            'tpl_value' =>"#code#=$code" //模板变量键值对的json类型字符串，根据实际情况修改
        );

        $paramstring = http_build_query($params);
        $content = $this->juheCurl($url, $paramstring);
        $result = json_decode($content, true);
        if ($result['error_code'] == 0) {
           // var_dump($result);
            db('user_sms')->insert(
                [
                    'phone'=>$data['phone'],
                    'code'=>$code,
                    'create_time'=>time(),
                    'wxapp_id'=>10001,
                    'text'=>json_encode($result),
                    ]
            );
            return $this->renderSuccess('发送成功');
        } else {
            $this->renderError('今日发送短信超过限制数量');
        }
    }


    /**
     * 请求接口返回内容
     * @param  string $url [请求的URL地址]
     * @param  string $params [请求的参数]
     * @param  int $ipost [是否采用POST形式]
     * @return  string
     */
    public function juheCurl($url, $params = false, $ispost = 0)
    {
        $httpInfo = array();
        $ch = curl_init();

        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'JuheData');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                curl_setopt($ch, CURLOPT_URL, $url.'?'.$params);
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }
        $response = curl_exec($ch);
        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
}
